<template>
  <div class="wishlist-page">
    <header-nav />
    
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>您的账户</el-breadcrumb-item>
        <el-breadcrumb-item>我的心愿单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 统一导航菜单 -->
      <user-nav-menu active-menu="wishlist" />

      <!-- 心愿单内容 -->
      <div v-if="activeTab === 'wishlist'" class="wishlist-container">
        <h1>我的心愿单</h1>
        
        <div v-if="loading" class="loading">
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="wishlist.length === 0" class="empty-wishlist">
          <el-empty description="心愿单还是空的">
            <el-button type="primary" @click="$router.push('/')">
              去购物
            </el-button>
          </el-empty>
        </div>
        
        <div v-else class="wishlist-grid">
          <el-card 
            v-for="item in wishlist" 
            :key="item.id" 
            class="wishlist-item"
            shadow="hover"
          >
            <div class="product-image">
              <el-image 
                :src="item.image" 
                :alt="item.name"
                fit="cover"
              />
            </div>
            <div class="product-info">
              <h3 @click="$router.push(`/product/${item.id}`)">
                {{ item.name }}
              </h3>
              <p class="price">¥{{ Number(item.price).toFixed(2) }}</p>
              <div class="actions">
                <el-button 
                  type="primary" 
                  @click="handleAddToCart(item)"
                >
                  加入购物车
                </el-button>
                <el-button 
                  type="danger" 
                  plain
                  @click="handleRemove(item.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import HeaderNav from '../components/HeaderNav.vue'
import UserNavMenu from '../components/UserNavMenu.vue'
import axios from '../utils/axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const wishlist = ref([])
const activeTab = ref('wishlist')
const orders = ref([])

// 注入 HeaderNav 组件的引用
const headerNav = inject('headerNav')

// 注入方法
const headerNavMethods = inject('headerNavMethods')

const fetchWishlist = async () => {
  try {
    loading.value = true
    const { data } = await axios.get('/api/wishlist')
    wishlist.value = data
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取心愿单失败')
  } finally {
    loading.value = false
  }
}

const handleRemove = async (productId) => {
  try {
    await axios.delete(`/api/wishlist/${productId}`)
    ElMessage.success('移除成功')
    await fetchWishlist()
    if (headerNavMethods) {
      await headerNavMethods.refreshWishlist()
    }
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('移除失败')
  }
}

const handleAddToCart = async (item) => {
  try {
    // 先检查商品是否已经在购物车中
    const { data: cartItems } = await axios.get('/api/cart')
    const existingItem = cartItems.find(cartItem => cartItem.product_id === item.id)
    
    if (existingItem) {
      await axios.put(`/api/cart/${existingItem.id}`, {
        quantity: existingItem.quantity + 1
      })
    } else {
      await axios.post('/api/cart', {
        productId: item.id,
        quantity: 1
      })
    }
    
    ElMessage.success('已添加到购物车')
    if (headerNavMethods) {
      await headerNavMethods.refreshCart()
    }
  } catch (error) {
    console.error('Error:', error)
    if (error.response?.status === 401) {
      ElMessage.error('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('添加失败')
    }
  }
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    const { data } = await axios.get('/api/orders')
    orders.value = data
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const types = {
    pending: 'warning',
    paid: 'primary',
    shipped: 'info',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const texts = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 确认收货
const handleConfirmReceive = async (orderId) => {
  try {
    await axios.post(`/api/orders/${orderId}/confirm`)
    ElMessage.success('确认收货成功')
    await fetchOrders()
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('操作失败')
  }
}

// 取消订单
const handleCancelOrder = async (orderId) => {
  try {
    await axios.post(`/api/orders/${orderId}/cancel`)
    ElMessage.success('订单已取消')
    await fetchOrders()
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('操作失败')
  }
}

// 处理菜单选择
const handleMenuSelect = (key) => {
  switch(key) {
    case 'orders':
      router.push('/account/orders')
      break
    case 'address':
      router.push('/address')
      break
    case 'wishlist':
      router.push('/wishlist')
      break
    case 'recent':
      router.push('/recent-views')
      break
    case 'details':
      router.push('/profile')
      break
  }
}

onMounted(() => {
  const tab = route.query.tab || 'wishlist'
  activeTab.value = tab
  if (tab === 'orders') {
    fetchOrders()
  } else {
    fetchWishlist()
  }
})
</script>

<style scoped>
.wishlist-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.breadcrumb {
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.wishlist-container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.wishlist-container h1 {
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
  font-weight: 500;
}

.wishlist-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
}

.wishlist-item {
  border: none;
  transition: all 0.3s ease;
}

.wishlist-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.product-image {
  height: 280px;
  overflow: hidden;
  border-radius: 8px 8px 0 0;
}

.product-image :deep(.el-image) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 20px;
}

.product-info h3 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 48px;
}

.product-info h3:hover {
  color: var(--el-color-primary);
}

.price {
  color: #ff6b6b;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.actions .el-button {
  flex: 1;
}

.empty-wishlist {
  text-align: center;
  padding: 60px 0;
}

.empty-wishlist .el-button {
  margin-top: 20px;
}

@media (max-width: 1440px) {
  .main-content {
    max-width: 1200px;
  }
}

@media (max-width: 1200px) {
  .wishlist-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .wishlist-grid {
    grid-template-columns: 1fr;
  }
  
  .product-image {
    height: 200px;
  }
}

/* 添加导航菜单样式 */
.nav-menu {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.account-menu {
  border: none;
  padding: 0 20px;
}

/* 添加菜单项悬停效果 */
:deep(.el-menu-item:hover) {
  background-color: #f5f7fa;
}

:deep(.el-menu-item.is-active) {
  color: var(--el-color-primary);
  border-bottom-color: var(--el-color-primary);
}

.orders-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.orders-container h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
  font-weight: 500;
}
</style> 